#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sqlite3

class DataBase():
    SHOW_SQL = True
    def Connect(self, db='database.db'):

        conn = sqlite3.connect(db)
        return conn
        
    def close_all(self, conn, cu):

        try:
            if cu:
                cu.close()
        finally:
            if cu:
                cu.close()
            
    def CreateTable(self, conn, sql):
        if sql:
            cu = conn.cursor()
            if self.SHOW_SQL:
                print 'execute sql: %s' % sql
            cu.execute(sql)
            conn.commit()
            print 'Create table success!'
            self.close_all(conn, cu)
        else:
            print 'The sql is empty!'

    def DropTable(self, conn, table):
        if table:
            sql = ' DROP TABLE IF EXISTS ' + table
            if self.SHOW_SQL:
                print 'Execute sql: %s' % sql
            cu = conn.cursor()
            ce.execute(sql)
            conn.commit()
            print 'Drop table: %s OK!' % table
            self.close_all(conn, cu)
        else:
            print 'The table name is empty!'

    def InsertData(self, conn, sql, data):
        if sql:
            if data:
                cu = conn.cursor()
                for d in data:
                    if self.SHOW_SQL:
                        print 'Execute sql: %s with data: %s' % (sql, data)
                    cu.execute(sql,d)
                conn.commit()
                self.close_all(conn, cu)
            else:
                print 'The data is empty!'
        else:
            print 'The sql is empty!'
            
    def GetAll(self, conn, sql):
        if sql:
            if self.SHOW_SQL:
                print 'Execute sql: %s' % sql
            cu = conn.cursor()
            ce.execute(sql)
            recodes = cu.fetchall()
            if len(recodes) > 0:
                for r in recodes:
                    print r
            self.close_all(conn, cu)

            return recodes, len(recodes)
        else:
            print 'The sql is empty!'

    def UpdateData(self, conn, sql, data):
        if sql:
            if data:
                cu = conn.cursor()
                for d in data:
                    if self.SHOW_SQL:
                        print 'Execute sql: %s' % sql
                    cu.execute(sql,d)
                conn.commit()
                #self.close_all(conn, cu)
            else:
                print 'The data is empty!'
        else:
            print 'The sql is empty!'
